package com.nbgroup.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nbgroup.mapper.OperlogMapper;
import com.nbgroup.pojo.common.PageResult;
import com.nbgroup.pojo.dto.PageOperLogDto;
import com.nbgroup.pojo.vo.OperLogVo;
import com.nbgroup.service.OperlogService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class OperlogServiceImpl implements OperlogService {
    @Autowired
    private OperlogMapper operlogMapper;

    @Override
    public PageResult list(PageOperLogDto dto) {
        dto.check();
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        Page<OperLogVo> p = operlogMapper.list(dto);

        PageResult pageResult = new PageResult();
        pageResult.setMsg("查询成功");
        pageResult.setCode(200);
        pageResult.setTotal(p.getTotal());
        pageResult.setRows(p.getResult());
        pageResult.setParams(pageResult.getParams());

        return pageResult;
    }

    @Override
    public void delete(List<Integer> ids) {
        operlogMapper.delete(ids);
    }

    @Override
    public void clean() {
        operlogMapper.clean();
    }

    @Override
    public void export(List<Integer> ids) throws IOException {

        List<OperLogVo> l = operlogMapper.getInfo(ids);

        XSSFWorkbook excel = new XSSFWorkbook();
        XSSFSheet sheet = excel.createSheet("0");

        XSSFRow row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("用户名");
        row1.createCell(1).setCellValue("请求方式");
        row1.createCell(2).setCellValue("访问地址");
        row1.createCell(3).setCellValue("模块名称");
        row1.createCell(4).setCellValue("登录ip");
        row1.createCell(5).setCellValue("操作时间");

        for (int i = 1; i < ids.size(); i++) {
            XSSFRow row = sheet.createRow(i);

            for (OperLogVo operLogVo : l) {
                row.createCell(0).setCellValue(operLogVo.getOperName());
                row.createCell(1).setCellValue(operLogVo.getRequestMethod());
                row.createCell(2).setCellValue(operLogVo.getOperUrl());
                row.createCell(4).setCellValue(operLogVo.getTitle());
                row.createCell(3).setCellValue(operLogVo.getOperIp());
                row.createCell(4).setCellValue(String.valueOf(operLogVo.getOperTime()));
            }
        }

        FileOutputStream out = new FileOutputStream(new File("d:\\log.xlsx"));
        excel.write(out);

        out.flush();
        out.close();
        excel.close();
    }
}
